// System
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

// Application
using EasySeries.Metier.Compareurs;
using EasySeries.Metier.Entites;
using EasySeries.Metier.Services;
using System.Collections;
using EasySeries.Dal.HandlerXml;

namespace EasySeries
{
    public partial class FrmPrincipale : Form
    {
        private bool dgvSeriesLoaded = false;
        private bool dgvAbonnementsLoaded = false;
        private Handler ab_H = new AbonnementHandler();
        private AbonnementService As = new AbonnementService();

        public FrmPrincipale()
        {
            InitializeComponent();
            tbNom.Select();
        }

        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void updateDgvAbonnements()
        {
            IList<Abonnement> abonnements = (IList<Abonnement>)Program.ContexteApplicatif["easyseries.abonnements"];

            if (!dgvAbonnementsLoaded && abonnements.Count == 0)
                return;

            if (dgvAbonnements.DataSource != null)
                dgvAbonnements.DataSource = null;

            dgvAbonnements.DataSource = abonnements;
        }

        public void updateDgvSeries()
        {
            IList<Serie> series = (IList<Serie>)Program.ContexteApplicatif["easyseries.series"];

            if (!dgvSeriesLoaded && series.Count == 0)
                return;

            if (dgvSeries.DataSource != null)
                dgvSeries.DataSource = null;

            dgvSeries.DataSource = series;

            toggleBtnDetail();
            toggleBtnDelete();

            tbNom.Text = "";
        }

        private void FrmPrincipale_Load(object sender, EventArgs e)
        {
            // Initialisation des abonnements
            As.initAbonnements();
            updateDgvAbonnements();
            dgvAbonnementsLoaded = true;

            bgwSeries.RunWorkerAsync();
                
        }

        private void tbNom_TextChanged(object sender, EventArgs e)
        {
            if (!dgvSeriesLoaded)
                return;

            try
            {
                Regex re = new Regex(tbNom.Text, RegexOptions.IgnoreCase);

                IList<Serie> series = (IList<Serie>)Program.ContexteApplicatif["easyseries.series"];
                IList<Serie> seriesFound = new List<Serie>();

                foreach (Serie serie in series)
                {
                    Match match = re.Match(serie.Name);

                    if (match.Success)
                        seriesFound.Add(serie);
                }

                dgvSeries.DataSource = seriesFound;
            }
            catch (Exception ex)
            {
                dgvSeries.DataSource = new List<Serie>();
            }
        }

        private void dgvSeries_DoubleClick(object sender, EventArgs e)
        {
            if (!dgvSeriesLoaded)
                return;

            FrmEpisodes frm = new FrmEpisodes((Serie)dgvSeries.SelectedRows[0].DataBoundItem);
            frm.Mainframe = this;

            frm.ShowDialog();
        }

        private void tcOnglets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tcOnglets.SelectedTab == tpAbonner)
            {
                Text = "EasySeries - S'abonner";
                tbNom.Select();
            }
            else
                Text = "EasySeries - Mes series";

            /*if (Text.Equals("EasySeries - S'abonner"))
                Text = "EasySeries - Mes series";
            else
                Text = "EasySeries - S'abonner";*/
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!dgvSeriesLoaded)
                return;

            Abonnement abo = (Abonnement)dgvAbonnements.SelectedRows[0].DataBoundItem;
            ab_H.Remove(abo);
            //Abonnement_Parsing.RemoveAbonnement(abo);
            ((IList<Abonnement>)Program.ContexteApplicatif["easyseries.abonnements"]).Remove(abo);
            updateDgvAbonnements();

            IList<Serie> series = (IList<Serie>)Program.ContexteApplicatif["easyseries.series"];

            series.Add(abo.Serie);
            ArrayList.Adapter((IList)series).Sort(new SerieCompareur());
            Program.ContexteApplicatif["easyseries.series"] = series;
            //((IList<Serie>)Program.ContexteApplicatif["easyseries.series"]).Add(abo.Serie);
            
            updateDgvSeries(); //Il faut rajouter la serie de l' abonnement ds la liste des series
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FrmPreferences frmPref = new FrmPreferences();
            frmPref.ShowDialog();
        }

        private void tbNom_KeyDown(object sender, KeyEventArgs e)
        {
            if (!dgvSeriesLoaded)
                return;

            if (e.KeyCode == Keys.Down)
            {
                if (dgvSeries.CurrentRow.Index < dgvSeries.Rows.Count - 1)
                {
                    dgvSeries.CurrentCell = dgvSeries.Rows[dgvSeries.CurrentRow.Index + 1].Cells[0];
                }
                e.Handled = true;
            }

            if (e.KeyCode == Keys.Up)
            {
                if (dgvSeries.CurrentRow.Index > 0)
                {
                    dgvSeries.CurrentCell = dgvSeries.Rows[dgvSeries.CurrentRow.Index - 1].Cells[0];
                }
                e.Handled = true;
            }

            if (e.KeyCode == Keys.Enter)
            {
                dgvSeries_DoubleClick(sender, e);
                e.Handled = true;
            }

            if (e.KeyCode == Keys.F5)
            {
                btnRafraichir_Click(sender, e);
                e.Handled = true;
            }
        }

        private void dgvSeries_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dgvSeries_DoubleClick(sender, e);
                e.Handled = true;
            }

            if (e.KeyCode == Keys.F5 && btnRafraichir.Enabled)
            {
                btnRafraichir_Click(sender, e);
                e.Handled = true;
            }
        }

        private void bgwSeries_DoWork(object sender, DoWorkEventArgs e)
        {
            // Initialisation de la liste des series sans abonnement
            tmrConnec.Start();
            SerieService.getSeriesWithoutAbonnement(bgwSeries, e);
            tmrConnec.Stop();
        }

        private void bgwSeries_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pbLoader.Hide();
            if (e.Error == null && !e.Cancelled)
            {
                updateDgvSeries();
                dgvSeriesLoaded = (dgvSeries.Rows.Count != 0);
            }
            else
            {
                lblErrors.Show();
            }

            btnRafraichir.Enabled = true;
        }

        private void toggleBtnDetail()
        {
            btnDetail.Enabled = (dgvSeries.Rows.Count != 0);
        }

        private void toggleBtnDelete()
        {
            btnDelete.Enabled = (dgvAbonnements.Rows.Count != 0);
        }

        private void parametresToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmPreferences frmPreferences = new FrmPreferences();
            frmPreferences.ShowDialog();
        }

        private void tmrConnec_Tick(object sender, EventArgs e)
        {
            bgwSeries.CancelAsync();
            tmrConnec.Stop();
        }

        private void btnRafraichir_Click(object sender, EventArgs e)
        {
            if (!bgwSeries.IsBusy)
            {
                if (lblErrors.Visible)
                    lblErrors.Hide();

                dgvSeries.DataSource = null;

                dgvSeriesLoaded = false;
                pbLoader.Show();

                bgwSeries.RunWorkerAsync();
            }
        }

        private void aProposToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string version = "0,1";
            FrmAPropos frm = new FrmAPropos(version.Replace(",", "."), "http://emmanueldetaillac.fr");
            frm.ShowDialog();
        }
    }
}